using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using Yoozoo.Mars.Got.SpriteAnim;

namespace Yoozoo.Gameplay.RTS
{
    public class SpriteAnimationEditor : EditorWindow
    {
        public static SpriteAnimationEditor m_window;

        private class AnimData
        {
            public string name;
            public int id;
            public Dictionary<int, ActionData> actions = new Dictionary<int, ActionData>();
        }

        private class ActionData
        {
            public string name;
            public SPRITE_ACTION_ENUM type;
            public int frames;//帧数
            public int averageFrameTime;//每帧持续时间
            public int keyFrame;//事件点
            public List<int> frameTimes;
            public bool isUseAverageFrame;
        }

        private static string attackFrameTime;
        private static string idleFrameTime;
        private static Dictionary<int, AnimData> dic = new Dictionary<int, AnimData>();

        
        static List<int> soldiers = new List<int>
        {
            411011,
            411021,
            411031,
            411041,
        };
        [MenuItem("GTATools/GamePlay/RTS/FrameAnimationEditor")]
        public static void Init()
        {
            m_window = (SpriteAnimationEditor)EditorWindow.GetWindow(typeof(SpriteAnimationEditor), false, "序列帧编辑器", true);
            m_window.Show();
            InitConfig();
            //RefreshDic();
        }

        private static void InitConfig()
        {
            if (dic.Count > 0)
            {
                return;
            }
            for (int i = 0; i < soldiers.Count; i++)
            {
                AnimData data = new AnimData();
                data.id = soldiers[i];
                data.name = "第" + (i+1) + "排" + data.id;
                var text = AssetDatabase.LoadAssetAtPath<TextAsset>("Assets/Arts/FrameAnimationConfig/" + soldiers[i] + ".txt");
                var anims = text.text.Split('\n');
                for (int j = 0; j < anims.Length; j++)
                {
                    var attrs = anims[j].Split(',');
                    if (attrs.Length <= 0)
                    {
                        continue;
                    }
                    string name = string.Empty;
                    List<int> frameTimes = new List<int>();
                    int averageTime = 0;
                    for (int k = 0; k < attrs.Length; k++)
                    {
                        if (k == 0)
                        {
                            name = attrs[k];
                        }
                        else if (k == 1)
                        {
                            var strs = attrs[k].Split('_');
                            if (strs.Length > 0)
                            {
                                int.TryParse(strs[0], out averageTime);
                            }
                        }
                        else
                        {
                            int time = 0;
                            if (int.TryParse(attrs[k], out time))
                            {
                                frameTimes.Add(time);
                                if (averageTime == 0)
                                {
                                    averageTime = time;
                                }
                            }
                        }
                    }
                    if (frameTimes.Count <= 0)
                    {
                        continue;
                    }
                    var type = GetTypeByName(name);
                    var action = new ActionData
                    {
                        type = type,
                        frames = frameTimes.Count,
                        averageFrameTime = averageTime,
                        isUseAverageFrame = false,
                        name = name,
                        frameTimes = frameTimes,
                    };
                    data.actions.Add((int)type,action);
                }
                dic.Add(soldiers[i],data);
            }
        }
        
        /*private static void RefreshDic()
        {
            dic.Clear();
            for (int i = 0; i < soldiers.Count; i++)
            {
                AnimData data = new AnimData();
                string soldierName = BattleUtils.GetSoldierModelNameById(soldiers[i]);
                data.name = soldierName + soldiers[i];
                data.id = soldiers[i];
                var creator = ArmyManager.GetCreator(soldierName);
                foreach (var item in creator.SpriteDicEx.Values)
                {
                    for (int j = 0; j < item.spriteData.Length; j++)
                    {
                        var spd = item.spriteData[j];
                        int type = j - 2;
                        string name = GetActionNameByType(j - 2);
                        if (spd.animData is null || spd.animData.Length == 0 || string.IsNullOrEmpty(name))
                        {
                            
                        }
                        else
                        {
                            int frames = BattleSpriteHelper.GetTotalFrames(soldiers[i],(SPRITE_ACTION_ENUM)type);
                            int frameTime = BattleSpriteHelper.GetFrameTime(soldiers[i],(SPRITE_ACTION_ENUM)type);
                            //int keyFrame = BattleSpriteHelper.GetKeyFramTime(soldiers[i],(SPRITE_ACTION_ENUM)type);
                            var action = new ActionData
                            {
                                type = (SPRITE_ACTION_ENUM) type,
                                frames = frames,
                                frameTime = frameTime,
                                name = name,
                                frameTimes = new List<int>(),
                            };
                            data.actions.Add(j-2,action);
                        }
                    }
                    dic.Add(soldiers[i],data);
                }
            }
        }*/

        public void OnGUI()
        {
            if (m_window == null)
            {
                Init();
            }
            EditorGUILayout.BeginHorizontal("HelpBox");
            if (GUILayout.Button("创建",GUILayout.Width(100)))
            {
                RTSTest.CreateArmy();
                //RefreshDic();
            }
            if (GUILayout.Button("Attack",GUILayout.Width(100)))
            {
                RTSTest.TestAttack();
            }
            if (GUILayout.Button("应用",GUILayout.Width(100)))
            {
                foreach (var item in dic.Values)
                {
                    foreach (var action in item.actions.Values)
                    {
                        var list = new List<int>();
                        for (int i = 0; i < action.frameTimes.Count; i++)
                        {
                            if (action.isUseAverageFrame)
                            {
                                list.Add(action.averageFrameTime);
                            }
                            else
                            {
                                list.Add(action.frameTimes[i]);
                            }
                        }
                        //BattleSpriteHelper.SetFrameTime(BattleUtils.GetSoldierModelNameById(item.id),action.type,list);
                    }
                }

                //BattleSpriteHelper.RefreshAnimTimeDic();
            }
            if (GUILayout.Button("导出",GUILayout.Width(100)))
            {
                foreach (var item in dic.Values)
                {
                    string data = string.Empty;
                    foreach (var action in item.actions.Values)
                    {
                        string actionData = string.Empty;
                        actionData += action.name + ",";
                        actionData += action.averageFrameTime + "_" + ",";
                        for (int i = 0; i < action.frameTimes.Count; i++)
                        {
                            float frameTime = action.frameTimes[i];
                            if (action.isUseAverageFrame)
                            {
                                frameTime = action.averageFrameTime;
                            }
                            actionData += frameTime + ",";
                        }
                        data += actionData;
                        data += "\r\n";
                        //BattleSpriteHelper.SetFrameTime(BattleUtils.GetSoldierModelNameById(item.id),action.type,action.frameTimes);
                    }
                    if (!Directory.Exists("Assets/Arts/FrameAnimationConfig"))
                    {
                        Directory.CreateDirectory("Assets/Arts/FrameAnimationConfig");
                    }
                    FileStream aFile = new FileStream("Assets/Arts/FrameAnimationConfig/" + item.id +  ".txt", FileMode.OpenOrCreate);
                    StreamWriter sw = new StreamWriter(aFile);
                    sw.Write (data);
                    sw.Close();
                    sw.Dispose();
                }
            }
            EditorGUILayout.EndHorizontal();
            foreach (var item in dic.Values)
            {
                string name = item.name;
                EditorGUILayout.Space();
                EditorGUILayout.BeginHorizontal("HelpBox");
                GUILayout.Label(name,GUILayout.Width(100));
                GUILayout.Label("使用平均速度",GUILayout.Width(100));
                EditorGUILayout.Space();
                EditorGUILayout.Space();
                EditorGUILayout.Space();
                EditorGUILayout.Space();
                GUILayout.Label("每帧速度",GUILayout.Width(100));
                GUILayout.FlexibleSpace ();	
                EditorGUILayout.EndHorizontal();
                foreach (var action in item.actions.Values)
                {
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Label(action.name,GUILayout.Width(100));
                    action.isUseAverageFrame = GUILayout.Toggle(action.isUseAverageFrame, GUIContent.none);
                    GUI.enabled = action.isUseAverageFrame;
                    string average = action.averageFrameTime.ToString();
                    average = GUILayout.TextField(average, GUILayout.Width(100));
                    int av = 0;
                    int.TryParse(average,out av);
                    action.averageFrameTime = av;
                    EditorGUILayout.Space();
                    GUI.enabled = !action.isUseAverageFrame;
                    for (int i = 0; i < action.frameTimes.Count; i++)
                    {
                        string frameTime = action.frameTimes[i].ToString();
                        frameTime = GUILayout.TextField(frameTime,GUILayout.Width(100));
                        int ft = 0;
                        int.TryParse(frameTime,out ft);
                        action.frameTimes[i] = ft;
                    }

                    GUI.enabled = true;
                    GUILayout.FlexibleSpace ();	
                    EditorGUILayout.EndHorizontal();
                }
            }
           
        }

        private static Dictionary<int,string> animNameDic=  new Dictionary<int, string>
        {
            {1,"Attack"},
            {2,"Dead"},
            {3,"Idle"},
            {4,"Run"},
            {5,"Attack2"},
        };
        
        private static string GetActionNameByType(int type)
        {
            string name = string.Empty;
            animNameDic.TryGetValue(type, out name);
            return name;
        }

        private static SPRITE_ACTION_ENUM GetTypeByName(string name)
        {
            SPRITE_ACTION_ENUM rt = SPRITE_ACTION_ENUM.RUN;
            foreach (var item in animNameDic)
            {
                if (item.Value == name)
                {
                    rt = (SPRITE_ACTION_ENUM) item.Key;
                    break;
                }
            }
            return rt;
        }
    }
}